/*
 * kProcessorManager.cpp
 *
 *  Created on: Mar 16, 2012
 *      Author: kylintse
 */

#include "kProcessorManager.h"

kProcessManager::kProcessManager(bool debug)
	: m_debug(debug)
{
	qRegisterMetaType<QProcess::ExitStatus>("QProcess::ExitStatus");
	m_env=QProcessEnvironment::systemEnvironment();
	if(debug)
	{
		m_mpr310Program="/app/MPR310";
		m_argvMpr310<<"-qws"<<"-nomouse"<<"-nfs"<<"-default";
	}
	else
	{
		m_mpr310Program="/mnt/jffs2/Mpr310/MPR310";
		m_argvMpr310<<"-nomouse"<<"-config=/mnt/jffs2/Mpr310/config";

		QFile paramFile;
		QDataStream ds;

		paramFile.setFileName("/mnt/jffs2/Mpr310/config/switch.ky");
		if(!paramFile.open(QIODevice::ReadOnly))
		{
			m_argvSwitch<<"-IP=192.168.1.2"<<"Type=Moxa";
		}
		else
		{
			ds.setDevice(&paramFile);
			QString switchAddr,switchType;
			ds>>switchAddr>>switchType;

			m_argvSwitch<<QString("IP=%1").arg(switchAddr)<<QString("Type=%1").arg(switchType);

			paramFile.close();
		}
	}
}

kProcessManager::~kProcessManager()
{

}

void kProcessManager::run()
{
	m_procMpr310=new QProcess;
	m_procMpr310->setProcessChannelMode(QProcess::ForwardedChannels);
	connect(m_procMpr310,SIGNAL(finished(int,QProcess::ExitStatus)),
			this,SLOT(restartProcMpr310(int,QProcess::ExitStatus)),Qt::DirectConnection);

	m_procMpr310->start("MPR310",m_argvMpr310);

	if(!m_procMpr310->waitForStarted(5000))
	{
		qWarning()<<"Mpr310 start failed"<<m_procMpr310->error()<<m_procMpr310->environment();
	}

	if(!m_debug)
	{
		m_procSwitch=new QProcess;
		m_procSwitch->setProcessChannelMode(QProcess::ForwardedChannels);
		connect(m_procSwitch,SIGNAL(finished(int,QProcess::ExitStatus)),
			this,SLOT(restartProcSwitch(int,QProcess::ExitStatus)),Qt::DirectConnection);

		m_procSwitch->start("SwitchManager",m_argvSwitch);
	}

	exec();

	m_procMpr310->kill();
	m_procMpr310->waitForFinished(5000);

	if(!m_debug)
	{
		m_procSwitch->kill();
		m_procSwitch->waitForFinished(5000);
	}

	delete m_procMpr310;
}

void kProcessManager::restartProcMpr310(int,QProcess::ExitStatus)
{
	qWarning()<<"restartProcess Mpr310";
	m_procMpr310->start("MPR310",m_argvMpr310);
	if(!m_procMpr310->waitForStarted(5000))
	{
		qWarning()<<"Mpr310 start failed"<<m_procMpr310->error()<<m_procMpr310->environment();
	}
}

void kProcessManager::restartProcSwitch(int,QProcess::ExitStatus)
{
	qWarning()<<"restartProcess SwitchManager";
	m_procSwitch->start("SwitchManager",m_argvSwitch);
	if(!m_procSwitch->waitForStarted(5000))
	{
		qWarning()<<"SwitchManager start failed"<<m_procSwitch->error()<<m_procSwitch->environment();
	}
}

